package com.authsphere.security.common.logging;

import com.authsphere.logging.common.collector.LogCollector;
import com.authsphere.logging.common.entity.LogDetail;
import com.authsphere.security.common.logging.factory.LogDetailFactory;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import java.io.IOException;

/**
 * @program: AuthSphere
 * @description:
 * @author: YuKai Fan
 * @create: 2025/3/24 17:08
 **/
public abstract class LoggingAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private LogCollector<LogDetail> logCollector;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        try {
            if (logCollector != null) {
                logCollector.collect(LogDetailFactory.build(request, response, authentication, null));
            }
        } finally {
            doAuthenticationSuccess(request, response, authentication);
        }
    }


    public void setLogCollector(LogCollector<LogDetail> logCollector) {
        this.logCollector = logCollector;
    }

    protected abstract void doAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication);
}
